package com.duobaoyu.dby.supply.db.config;

import com.duobaoyu.dby.supply.db.entity.config.OperationLog;
import com.duobaoyu.dby.supply.db.entity.message.*;
import com.google.common.collect.Sets;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;
import java.util.Set;

/**
 * @author liyang
 * @version 1.0.0
 * @ClassName ApplicationRunnerImpl
 * @createTime 12:48:00 2023/10/14
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class ApplicationRunnerImpl implements ApplicationRunner {

    private final MongoTemplate mongoTemplate;
    private static Set<Class<?>> MONGODB_COLLECTION = Sets.newHashSet(ChannelMessageOrder.class,SystemLog.class,
            ChannelMessageProduct.class, MqMessage.class, MqMessageConsumer.class, DelayMessage.class, OperationLog.class);
    @Override
    public void run(ApplicationArguments args) throws Exception {
        final String className = "class_name";
        Set<String> optionNames = args.getOptionNames();
        for (String optionName : optionNames) {
            if(Objects.equals(className,optionName)) {
                List<String> classNames = args.getOptionValues(optionName);
                if(CollectionUtils.isNotEmpty(classNames)) {
                    for (String name : classNames) {
                        try {
                            Class<?> clazz = Class.forName(name);
                            MONGODB_COLLECTION.add(clazz);
                        } catch (Throwable e) {
                            log.warn(name.concat("not exist"));
                        }
                    }
                }
            }

        }
        for (Class<?> clazz : MONGODB_COLLECTION) {
            if(!mongoTemplate.collectionExists(clazz)) {
                mongoTemplate.createCollection(clazz);
            }
        }
    }
}
